package com.yksj.healthtalk.ui.chatting;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.cropimage.CropUtils;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import org.handmark.pulltorefresh.library.PullToRefreshListView;
import org.json.JSONArray;
import org.universalimageloader.utils.StorageUtils;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.yksj.healthtalk.adapter.ChatAdapter;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.ChatInputControlFragment;
import com.yksj.healthtalk.comm.ChatInputControlFragment.ChatInputControlListener;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog.OnDilaogClickListener;
import com.yksj.healthtalk.comm.ImageGalleryActivity;
import com.yksj.healthtalk.comm.SingleBtnFragmentDialog;
import com.yksj.healthtalk.db.ChatUserHelper;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.entity.GroupInfoEntity;
import com.yksj.healthtalk.entity.MessageEntity;
import com.yksj.healthtalk.media.ArmMediaPlay;
import com.yksj.healthtalk.media.ArmMediaPlay.ArmMediaPlayListener;
import com.yksj.healthtalk.media.ArmMediaRecord;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.BinaryHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.CoreService;
import com.yksj.healthtalk.services.CoreService.CoreServiceBinder;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.friend.DoctorMainActivity;
import com.yksj.healthtalk.ui.friend.FriendInformUI;
import com.yksj.healthtalk.ui.friend.FriendSearchAboutFriendActivity;
import com.yksj.healthtalk.ui.salon.SalonMemberListActivity;
import com.yksj.healthtalk.ui.setting.SettingWebUIActivity;
import com.yksj.healthtalk.ui.views.VUMeterView;
import com.yksj.healthtalk.utils.BitmapUtils;
import com.yksj.healthtalk.utils.DataParseUtil;
import com.yksj.healthtalk.utils.LogUtil;
import com.yksj.healthtalk.utils.SharePreUtils;
import com.yksj.healthtalk.utils.SystemUtils;
/**
 * 聊天UI
 * @author jack_tang
 * 
 */
public class ChatActivity extends BaseFragmentActivity implements 
	OnClickListener,ChatInputControlListener
	,ArmMediaPlayListener
	{
//	private final static String TAG = ChatActivity.class.getName();
	public  final static String KEY_PARAME = "parame";
	public  final static String KEY_CONTENT = "retgretting";
//	private final int TOP_REFRESH = 1;
//	private final int BOTTOM_REFRESH = 2;
	
	private Looper mLooper;
	private ChatHandler mChatHandler;
	private boolean isGroupChat = false;//是否是群聊
//	private boolean isPayed = true;//是否已经支付
	public String mChatId;//聊天id
	public String mUserId;//登陆者id
	private String registerNoteStr;//挂号提示
	
	private ImageView mChatBgImageV;//聊天背景
	public VUMeterView mChatVm;
	private PopupWindow mPopupWindow;
	private PopupWindow mOptionWindow;
	
	public ArmMediaPlay mediaPlay;
	public ArmMediaRecord mediaRecord;
	
	ChatInputControlFragment mChatInputControlFragment;
	GroupInfoEntity mGroupInfoEntity;
	CustomerInfoEntity mCustomerInfoEntity;
	
	View mChatMenuV;
	MessageEntity mPlayingEntity;
	ListView mListView;
	ChatAdapter mChatAdapter;
	PullToRefreshListView mPullToRefreshListView;
	ChatUserHelper mDbUserHelper;//数据库操作
	CoreService mPushService;//后台服务对象
	AppData mAppData;
	File mChatBgFile;//聊天背景图片
	
	//list view长按事件
	@SuppressWarnings("deprecation")
	final GestureDetector mGestureDetector = new GestureDetector(new ChatGestureListener(){
		public void onLongPress(MotionEvent e) {
			boolean isEditor = mChatAdapter.isEditor();
			if(isEditor){
				mChatAdapter.onUnEditorMode();
			}else{
				mChatAdapter.onEditorMode();
			}
			mChatInputControlFragment.onChangeEditorMode(!isEditor);
		};
	});
	
	//后台服务绑定
	final ServiceConnection mServiceConnection = new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {
		}
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			CoreServiceBinder binder = (CoreServiceBinder)service;
			mPushService = binder.getService();
			mChatHandler.sendEmptyMessage(1006);//发送一些转发的消息
		}
	};
	
	//注册通知
	final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if(isFinishing())return;
			String action = intent.getAction();
			if(action.equals(CoreService.ACTION_MESSAGE)){//新消息
				String senderId = intent.getStringExtra("senderId");//发送者id
				if(mChatId.equals(senderId)){//更新到界面上
					mChatHandler.sendEmptyMessage(1000);
					//弹出收费框
				}
			}else if(CoreService.ACTION_OFFLINE_MESSAGE.equals(action)){
				mChatHandler.sendEmptyMessage(1000);
			}else if(CoreService.ACTION_PAY_MESSAGE.equals(action)){
				String senderId = intent.getStringExtra("senderId");//发送者id
				String note = intent.getStringExtra("tickNote");
				if(mChatId.equals(senderId)){//更新到界面上
					Message message = mChatHandler.obtainMessage();
					message.obj = note;
					message.what = 1005;
					mChatHandler.sendMessage(message);
				}
			}
		}
	};
	/**
	 * 消息处理
	 * @author zhao
	 */
	private final class ChatHandler extends Handler{
		public ChatHandler(Looper looper) {
			super(looper);
		}
		@Override
		public void handleMessage(Message msg) {//异步线程
			switch(msg.what){
			case 1000://获取的新消息
				final List<MessageEntity> list = onLoadMesgForCache();
				if(list == null || list.size() == 0) return;
				deleteOffLineMessage(list,true);
				break;
			case 9999://缓存消息(不需要加载到adapter中去)
				final List<MessageEntity> lists = onLoadMesgForCache();
				if(lists == null || lists.size() == 0) return;
				deleteOffLineMessage(lists,false);
				break;
			case 1001://db获取消息
				final List<MessageEntity> entities = mDbUserHelper.queryChatMessageByAfterId(mUserId,mChatId,isGroupChat,(String)msg.obj,"10");
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						if(entities != null && entities.size()>0){
							mChatAdapter.addCollectionToTop(entities);
						}
						mPullToRefreshListView.onRefreshComplete();
					}
				});
				break;
			case 1002://全部删除
				if(isGroupChat){
					//群聊删除
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							HttpRestClient.deleteGroupMessages(mChatId,1,null,new AsyncHttpResponseHandler(ChatActivity.this){
								@Override
								public void onSuccess(int statusCode, String content) {
									if("0".equals(content)){
//										onFailure(null,null);
									}else{
										mChatAdapter.onDeleteAll();
									}
								}
							});
						}
					});
				}else{
					//单聊删除
					mDbUserHelper.deleteAllMessageByChatId(mChatId,mUserId);
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							mChatAdapter.onDeleteAll();
						}
					});
				}
				break;
			case 1003://选中删除
				final List<MessageEntity> messageEntities = (List<MessageEntity>)msg.obj;
				if(isGroupChat){
					final StringBuffer messageBuffer = new StringBuffer();
					for (MessageEntity messageEntity : messageEntities) {
						String id = messageEntity.getId();
						if(id == null)continue;
						messageBuffer.append(id);
						messageBuffer.append(",");
					}
					//群聊删除
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							HttpRestClient.deleteGroupMessages(mChatId,0,messageBuffer.toString(),new AsyncHttpResponseHandler(ChatActivity.this){
								@Override
								public void onSuccess(int statusCode, String content) {
									mChatAdapter.onDeleteSelectedl(messageEntities);
								}
							});
						}
					});
				}else{
					//单聊删除
					mDbUserHelper.deleteChatMessage(messageEntities);
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							mChatAdapter.onDeleteSelectedl(messageEntities);
						}
					});
				}
				break;
			case 1005://收费框弹出
				final String note = (String)msg.obj;
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						onShowPayDialog(note);
					}
				});
				break;
			case 1006://发送一些转发的消息
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						if(getIntent().hasExtra(KEY_CONTENT) && mPushService!=null){
							String content = getIntent().getStringExtra(KEY_CONTENT);
							if(!TextUtils.isEmpty(content))onSendTxtMesg(content);
							getIntent().removeExtra(KEY_CONTENT);
						}
					}
				});

				break;
/*			case TOP_REFRESH:
				break;
			case BOTTOM_REFRESH:
				break;*/
			}
		}
	}
	
	//发送消息 表示已经看过
	private class RequestHttpSendMessage extends ObjectHttpResponseHandler{
		private JSONArray arrays;
		public RequestHttpSendMessage(JSONArray leavemessages) {
			this.arrays=leavemessages;
		}
		@Override
		public Object onParseResponse(String content) {
			try {
				org.json.JSONObject object=new org.json.JSONObject(content);
				if(1==object.optInt("error_code",-1)){
					
					List<String> strings=new ArrayList<String>();
					for (int i = 0; i < arrays.length(); i++) {
						HTalkApplication.getAppData().messageMap.remove(arrays.get(i).toString());
						strings.add(arrays.get(i).toString());
					}
					ChatUserHelper.getInstance().updateChatMesageDeleteState(strings);
					
				}else{
					LogUtil.e("=======CHAT", "聊天 发送删除离线消息失败");
				}
			} catch (Exception e) {
				LogUtil.e("=======CHAT", "聊天 发送删除离线消息失败");
			}
			return null;
		}
	}

	/**
	 * 加载历史消息
	 */
	private final OnRefreshListener2<ListView> mOnRefreshListener2 = new OnRefreshListener2<ListView>() {
		public void onPullDownToRefresh(org.handmark.pulltorefresh.library.PullToRefreshBase<ListView> refreshView) {
			if(isGroupChat){
				onLoadMesgForHttp();
			}else{
				onLoadMesgForDB();
			}
		};
		public void onPullUpToRefresh(org.handmark.pulltorefresh.library.PullToRefreshBase<ListView> refreshView) {
		};
	};

	/**
	 * 删除离线消息
	 * list 消息集合
	 * isAddList 是否将消息添加到adapter中
	 */
	private void deleteOffLineMessage(final List<MessageEntity> list,final boolean isAddList){
		final JSONArray leavemessages=new JSONArray();
		for (MessageEntity messageEntity : list) {
			String id = messageEntity.getServerId();
			if(id == null)continue;
			leavemessages.put(id);
		}
		runOnUiThread(new Runnable() {
			public void run() {
				HttpRestClient.doHttpDeleteLeaveOnlineMessage(SmartFoxClient.getLoginUserId(), leavemessages.toString(), new RequestHttpSendMessage(leavemessages));
				if(list != null && list.size() >0 && isAddList){
					mChatAdapter.addCollectionToEnd(list);
					mListView.setSelection(mChatAdapter.getCount());
				}else if(!isAddList && list != null){
					onLoadMesgForDB();
				}
				mPullToRefreshListView.onRefreshComplete();
			}
		});
	}
	
	
	
	/**
	 * 语音文件下载
	 * @author zhao
	 */
	protected class VoiceFileHttpResponseHandler extends BinaryHttpResponseHandler{
		final MessageEntity mEntity;
		public VoiceFileHttpResponseHandler(MessageEntity entity){
			mEntity = entity;
		}
		@Override
		public boolean onProcess(byte[] bytes)throws IOException {
			if(bytes == null || bytes.length == 0)throw new IOException("Save file fail"); 
			String fileName = StorageUtils.getFileName(mEntity.getContent());
			File file = StorageUtils.createVoiceFile(fileName);
			if(file == null)throw new IOException("Save file fail");
			FileOutputStream fileOutputStream = null;
			try{
				fileOutputStream = new FileOutputStream(file);
				fileOutputStream.write(bytes);
			}finally{
				if(fileOutputStream != null){
					fileOutputStream.flush();
					fileOutputStream.close();
				}
			}
			return false;
		}
		@Override
		public void onSuccess(int statusCode, byte[] binaryData) {
			super.onSuccess(statusCode, binaryData);
			if(mPlayingEntity == mEntity){//当前下载的等于需要播放的
				mPlayingEntity = null;
				mediaPlay.play(mEntity);
			}
		}
	}
	
	
	/**
	 * 群历史消息加载
	 */
	private void onLoadMesgForHttp(){
		int size = mChatAdapter.getCount();
		String serverid = null;//获取最大的id
		if(size == 0){
			serverid = String.valueOf(Long.MAX_VALUE);
		}else{
			serverid = mChatAdapter.getFirstMesgId();
		}
		HttpRestClient.doHttpQueryChatMesg(mChatId,serverid,"10",new ObjectHttpResponseHandler() {
			@Override
			public Object onParseResponse(String cotent) {
				List<MessageEntity> list = DataParseUtil.parseGroupMessage(cotent,mUserId);
				return list;
			}
			@Override
			public void onSuccess(int statusCode, Object response) {
				super.onSuccess(statusCode, response);
				if(response != null)mChatAdapter.addCollectionToTop((List<MessageEntity>)response);
			}
			@Override
			public void onFinish() {
				super.onFinish();
				mPullToRefreshListView.onRefreshComplete();
			}
		});
	}
	
	/**
	 * 从单聊中查询
	 */
	private void onLoadMesgForDB(){
//		String id = mChatAdapter.getFirstMesgId();
//		Message message = mChatHandler.obtainMessage();
//		message.what = 1001;
//		message.obj = id;
//		mChatHandler.sendMessage(message);
		int size = mChatAdapter.getCount();
		String serverid = null;//获取最大的id
		if(size == 0){
			serverid = String.valueOf(Long.MAX_VALUE);
		}else{
			serverid = mChatAdapter.getFirstMesgId();
		}
		
		//判断多美医生加载消息
		if(size==1 && mChatId .equals(SmartFoxClient.helperId))
			serverid = String.valueOf(Long.MAX_VALUE);
		
		
		HttpRestClient.doHttpQueryPersonChatMesg(mChatId,serverid,new ObjectHttpResponseHandler() {
			@Override
			public Object onParseResponse(String cotent) {
				List<MessageEntity> list = DataParseUtil.parseGroupMessage(cotent,mUserId);
				return list;
			}
			@Override
			public void onSuccess(int statusCode, Object response) {
				super.onSuccess(statusCode, response);
				if(response != null)mChatAdapter.addCollectionToTop((List<MessageEntity>)response);
			}
			@Override
			public void onFinish() {
				super.onFinish();
				mPullToRefreshListView.onRefreshComplete();
			}
		});
	}
	
	/**
	 * 从缓存中加载消息
	 */
	private List<MessageEntity> onLoadMesgForCache(){
		final List<MessageEntity> list = mAppData.messageCllection.get(mChatId);
		if(list != null)mAppData.messageCllection.remove(mChatId);
		return list;
	}
	
	/**
	 * 加载历史消息
	 */
	private void initHistoryMesg(){
		boolean bl = mAppData.messageCllection.containsKey(mChatId);
		if(bl){//从缓存中获取消息
			mChatHandler.sendEmptyMessage(9999);
		}else{
			if(isGroupChat){
				onLoadMesgForHttp();//群聊
			}else{
				//单聊
				if(SmartFoxClient.helperId.equals(mChatId)){
					final MessageEntity entity = new MessageEntity();
					entity.setType(MessageEntity.TYPE_TEXT);
					entity.setContent("您好，我是您的多美助理，将为您发送各类消息通知，请您及时查看。");
					entity.setSenderId(SmartFoxClient.helperId);
					entity.setReceiverId(SmartFoxClient.getLoginUserId());
					mDbUserHelper.insertChatMessage(entity);
					mChatAdapter.addNew(entity);
					mListView.setSelection(mChatAdapter.getCount());
					mPullToRefreshListView.onRefreshComplete();
				}else{
					onLoadMesgForDB();
				}	
			}
		}
	}
	
	private void saveMessage(MessageEntity messageEntity){//保存消息到db
		if(!isGroupChat){
			mDbUserHelper.insertChatMessage(messageEntity);
		}
	}
	
	public final void onUpdateSelectedNumber(int size){
		mChatInputControlFragment.onUpdateSelectedNumber(size);
	}
	
	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		initData(bundle);
		
		setContentView(R.layout.chat_layout);
		
		initUI();
		
		if(isGroupChat){
			//加入聊天室
			SmartFoxClient.sendJoinGroupChat(mChatId);
		}else{
			//聊天提示
			if(registerNoteStr  !=  null){
				TextView view= (TextView) findViewById(R.id.chat_content);
				view.setText(registerNoteStr);
				findViewById(R.id.chat_content).setVisibility(View.VISIBLE);
//				MessageEntity entity = new MessageEntity();
//				entity.setType(MessageEntity.TYPE_TIME);
//				entity.setContent(registerNoteStr);
//				mChatAdapter.addNew(entity);
//				mListView.setSelection(mChatAdapter.getCount());
			}else{
				findViewById(R.id.chat_content).setVisibility(View.GONE);
			}
			/*//聊天购买提示
			HttpRestClient.doHttpInitChat(mUserId,mChatId,new JsonsfHttpResponseHandler(){
				@Override
				public void onSuccess(int statusCode, JSONObject response) {
					String sendCode = response.getString("send_code");
					if(sendCode == null || sendCode.length() == 0)return;
					MessageEntity entity = new MessageEntity();
					entity.setType(MessageEntity.TYPE_TIME);
					entity.setContent(sendCode);
					List<MessageEntity> list = new ArrayList<MessageEntity>(1);
					list.add(entity);
					mChatAdapter.addCollectionToTop(list);
				}
			});*/
		}
		
		initHistoryMesg();
	}
	
	//当前需要复制的view
	TextView mCopyTxtV;
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		switch(v.getId()){
		case R.id.chat_content:
			mCopyTxtV = (TextView)v;
			menu.add(0, 1, 0, "复制");
			menu.add(0, 2, 0, "重发此消息");
			break;
		}
		super.onCreateContextMenu(menu, v, menuInfo);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case 1://复制
			if(mCopyTxtV  != null)
				SystemUtils.clipTxt(mCopyTxtV.getText(), this);
			return true;
		case 2:
			if(mCopyTxtV  != null)
				onSendTxtMesg(mCopyTxtV.getText().toString());
			break;
		}
		return super.onContextItemSelected(item);
	}
	
	@Override
	public void onContextMenuClosed(Menu menu) {
		mCopyTxtV = null;
		super.onContextMenuClosed(menu);
	}
	
	private void initUI(){
		initTitle();
		
		setBackBtn("返回",this);
		
		setRightMore(this);
		
		mChatBgImageV = (ImageView)findViewById(R.id.chat_bg);
		mChatVm = (VUMeterView)findViewById(R.id.chat_vm);
		mChatVm.setMediaRecord(mediaRecord);
		
		mChatInputControlFragment = (ChatInputControlFragment)getSupportFragmentManager().findFragmentById(R.id.input_control);
		mPullToRefreshListView = (PullToRefreshListView)findViewById(R.id.pull_refresh_listview);
		mPullToRefreshListView.setOnRefreshListener(mOnRefreshListener2);
		mListView = mPullToRefreshListView.getRefreshableView();
		mListView.setAdapter(mChatAdapter = new ChatAdapter(this,isGroupChat,mChatId));
		
		mListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_NORMAL);
		mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				switch(scrollState){
				case OnScrollListener.SCROLL_STATE_IDLE:
					if(view.getLastVisiblePosition() == (view.getCount()-1)){//最后一条显示状态
						mListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);//始终滑动到最后
					}else{
						mListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_DISABLED);
					}
					break;
				}
			}
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
			}
		});
		mListView.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return mGestureDetector.onTouchEvent(event);
			}
		});
		
		if(isGroupChat){
			titleTextV.setText( mGroupInfoEntity.getName());
		}else{
			if(mCustomerInfoEntity.isDoctor()){
				titleTextV.setText(mCustomerInfoEntity.getName()+"医生");
			}else{
				titleTextV.setText(mCustomerInfoEntity.getName());
			}
		}
		registerForContextMenu(mListView);
		//if(!isGroupChat)isPayedUser();
		//从支付宝页面过来的
		if(getIntent().hasExtra("pay_type")){
			SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(), "您可以咨询医生,如预约时间未到也可留言,离开此页面再次进入,请到\"我的壹健康-我的医生\"找该医生诊所");
		}
	}
	/**
	 * 弹出支付窗口
	 */
	private void onShowPayDialog(String note){
		DoubleBtnFragmentDialog.showDefault(getSupportFragmentManager(),  note, "知道了","现在去购买",new OnDilaogClickListener() {
			@Override
			public void onDismiss(DialogFragment fragment) {
				fragment.dismissAllowingStateLoss();
			}
			@Override
			public void onClick(DialogFragment fragment,View v) {
				toPay();
			}
		});
	}
	
	/** 
	 * 去购买医生服务
	 */
	public void toPay(){
		String name = getIntent().getComponent().getClassName();
		if(name.equals(DoctorMainActivity.class.getName())){
			onBackPressed();
		}else{
			Intent intent = new Intent(this,DoctorMainActivity.class);
			intent.putExtra("id",mChatId);
			startActivity(intent);
		}
	}
	
	/**
	 * 初始化数据
	 */
	private void initData(Bundle bundle){
		HTalkApplication.getApplication().cancelNotify();
		HandlerThread handlerThread = new HandlerThread("chathandler");
		handlerThread.start();
		mLooper = handlerThread.getLooper();
		mChatHandler = new ChatHandler(mLooper);
		mDbUserHelper = ChatUserHelper.getInstance();
		//录音,播放初始化
		mediaPlay = new ArmMediaPlay();
		mediaRecord = new ArmMediaRecord();
		mediaPlay.setMediaPlayListener(this);
		mAppData = HTalkApplication.getAppData();
		mUserId = SmartFoxClient.getLoginUserId();
		
		if(bundle != null){
			if(bundle.containsKey("group_entity")){
				mGroupInfoEntity = (GroupInfoEntity)bundle.getParcelable("group_entity");
				mChatId = mGroupInfoEntity.getId();
				isGroupChat = true;
			}else{
				mCustomerInfoEntity = (CustomerInfoEntity)bundle.getParcelable("user_entity");
				mChatId = mCustomerInfoEntity.getId();
				isGroupChat = false;
			}
		}else{
			
			registerNoteStr  =  getIntent().getStringExtra("NOTE");
			//isPayed = getIntent().getBooleanExtra("isPayed",false);//是否已经支付
			Object object = getIntent().getParcelableExtra(KEY_PARAME);
			if(object instanceof CustomerInfoEntity){//单聊
				mCustomerInfoEntity = (CustomerInfoEntity)object;
				mChatId = mCustomerInfoEntity.getId();
				isGroupChat = false;
			}else if(object instanceof GroupInfoEntity){//群聊
				mGroupInfoEntity  = (GroupInfoEntity)object;
				mChatId = mGroupInfoEntity.getId();
				isGroupChat = true;
			}
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			boolean b = mChatInputControlFragment.isAllPanelGone();//隐藏未隐藏的面板
			if(!b)return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	/**
	 * 绑定后台服务
	 */
	private void onBindService(){
		Intent intent = new Intent(this,CoreService.class);
		bindService(intent,mServiceConnection,Context.BIND_AUTO_CREATE);
	}
	
	/**
	 * 注册通知
	 */
	private void onRegisterReceiver(){
		IntentFilter filter = new IntentFilter();
		filter.addAction(CoreService.ACTION_MESSAGE);
		filter.addAction(CoreService.ACTION_PAY_MESSAGE);
		filter.addAction(CoreService.ACTION_OFFLINE_MESSAGE);
		if(SmartFoxClient.helperId.equals(mChatId))filter.addAction(CoreService.ACTION_GROUP_INVITE);//好友邀请
		registerReceiver(mReceiver, filter);
	}
	
	@Override
	protected void onStart() {
		onBindService();
		onRegisterReceiver();
		super.onStart();
	}
	
	@Override
	protected void onResume() {
		onSetBg();
		super.onResume();
	}
	
	@Override
	protected void onStop() {
		unregisterReceiver(mReceiver);
		if(mediaPlay.isPlaying()){
			mediaPlay.stop();
		}
		onReleaseBg();
		super.onStop();
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		if(mGroupInfoEntity != null)outState.putParcelable("group_entity",mGroupInfoEntity);
		if(mCustomerInfoEntity != null)outState.putParcelable("user_entity", mCustomerInfoEntity);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode,resultCode,data);
		switch(requestCode){
		case 3000://聊天背景设置相册获取
			if(resultCode == Activity.RESULT_OK){
				if (data != null) {
					Uri uri = data.getData();
					String scheme = uri.getScheme();
					String strFilePath = null;//图片地址
					// url类型content or file
					if ("content".equals(scheme)) {
						strFilePath = mChatInputControlFragment.getImageUrlByAlbum(uri);
					} else {
						strFilePath = uri.getPath();
					}
					onHandlerChatBg(strFilePath);
				}
			}
			break;
		case 3001://聊天背景设置相机获取
			if(resultCode == Activity.RESULT_OK){
				String strFilePath = mChatBgFile.getAbsolutePath();
				onHandlerChatBg(strFilePath);
			}
			mChatBgFile = null;
			break;
		}
	}
	
	@Override
	protected void onRestart() {
		super.onRestart();
		mChatHandler.sendEmptyMessage(1000);
	}
	    
	@Override
	protected void onDestroy() {
		unbindService(mServiceConnection);
		if(mLooper != null)mLooper.quit();
		if(mPopupWindow != null && mPopupWindow.isShowing())mPopupWindow.dismiss();
		if(mOptionWindow != null && mOptionWindow.isShowing())mOptionWindow.dismiss();
		mOptionWindow = null;
		mPopupWindow = null;
		if(isGroupChat)SmartFoxClient.sendLogoutGroup(mChatId);
		HTalkApplication.getApplication().cancelNotify();
		super.onDestroy();
	}
	
	@Override
	public void onClick(View v) {
		Intent intent;
		switch(v.getId()){
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.title_right2://
			mChatInputControlFragment.hideSoftBord();
			onShowOptionMenu(v);
			break;
		case R.id.popup_menu1://相册获取
			mPopupWindow.dismiss();
			onChatBgPhotoClick(v);
			break;
		case R.id.popup_menu2://相机获取图片
			mPopupWindow.dismiss();
			onChatBgCameraClick(v);
			break;
		case R.id.popup_menu3://使用默认图片
			mPopupWindow.dismiss();
			SharePreUtils.clearChatBg(this,mUserId,mChatId);
			onSetBg();
			break;	
		case R.id.popup_menu_cancel://退出
			mPopupWindow.dismiss();
			break;
		case R.id.popup_menu4://关注的人
			mPopupWindow.dismiss();
			onInviteFriend(1);
			break;
		case R.id.popup_menu5://邀请多么号,昵称
			mPopupWindow.dismiss();
			intent = new Intent(this,InviteByNameActivity.class);
			intent.putExtra("groupId", mChatId);
			startActivity(intent);
			break;
		case R.id.popup_menu6://邀请条件
			mPopupWindow.dismiss();
			onInviteFriend(3);
			break;
		case R.id.popup_menu7://邀请身边的人
			mPopupWindow.dismiss();
			onInviteFriend(4);
			break;
		case R.id.option_popmenu7://管理发言
		case R.id.option_popmenu1://删除对话
			boolean isEditor = mChatAdapter.isEditor();
			if(isEditor){
				mChatAdapter.onUnEditorMode();
			}else{
				mChatAdapter.onEditorMode();
			}
			mChatInputControlFragment.onChangeEditorMode(!isEditor);
			if(mOptionWindow != null)mOptionWindow.dismiss();
			break;
		case R.id.option_popmenu2://聊天背景
			mOptionWindow.dismiss();
			onShowBgPopUpMenu();
			break;
		case R.id.option_popmenu3://服务内容
			mOptionWindow.dismiss();
			intent = new Intent(this,SettingWebUIActivity.class);
			intent.putExtra("TextSize", 100);
			intent.putExtra("url", "http://www.h-tlk.com/JumpPage/JumpPageServlet?Type=DoctorServiceIntroduce");
			intent.putExtra("title", "服务内容");
			startActivity(intent);
			break;
		case R.id.option_popmenu4://邀请加入
			mOptionWindow.dismiss();
			onShowInvitePopUpMenu();
			break;
		case R.id.option_popmenu5://在线成员
			mOptionWindow.dismiss();
			onShowGroupListNumber();
			break;
		case R.id.option_popmenu6://禁止发言
			mOptionWindow.dismiss();
			intent = new Intent(this,ForbiddenWordsListActivity.class);
			intent.putExtra("groupId",mChatId);
			startActivity(intent);
			break;
/*		case R.id.option_popmenu8://黑名单
			mOptionWindow.dismiss();
			intent = new Intent(this,BlackFriendListActivity.class);
			intent.putExtra("groupId", mChatId);
			startActivity(intent);
			break;*/
		case R.id.option_popmenu9://医生资料
			mOptionWindow.dismiss();
			intent = new Intent(this,FriendInformUI.class);
			intent.putExtra("id", mCustomerInfoEntity.getId());
			startActivity(intent);
			break;
		/*case R.id.option_popmenu11://文件浏览
			mOptionWindow.dismiss();
			intent = new Intent(this,DocumentsChatActivity.class);
			intent.putExtra("groupId",mChatId);
			intent.putExtra("userId", mUserId);
			startActivityForResult(intent,-1);
			break;*/
		}
	}

	@Override
	public void onSendTxtMesg(String content) {
		MessageEntity messageEntity = new MessageEntity();
		messageEntity.setId(String.valueOf(System.currentTimeMillis()));
		messageEntity.setSenderId(mUserId);
		messageEntity.setReceiverId(mChatId);
		messageEntity.setType(MessageEntity.TYPE_TEXT);
		messageEntity.setSendFlag(true);
		messageEntity.setContent(content);
		messageEntity.setSendState(MessageEntity.STATE_PROCESING);
		saveMessage(messageEntity);
		mChatAdapter.addNew(messageEntity);
		mListView.setSelection(mChatAdapter.getCount());
		mPushService.onSendChatMessage(messageEntity, isGroupChat,MessageEntity.TYPE_TEXT);
	}

	@Override
	public void onSendLocationMesg(String longitude, String latitude,String address) {
		MessageEntity messageEntity = new MessageEntity();
		messageEntity.setSenderId(mUserId);
		messageEntity.setReceiverId(mChatId);
		messageEntity.setId(String.valueOf(System.currentTimeMillis()));
		messageEntity.setType(MessageEntity.TYPE_LOCATION);
		messageEntity.setSendState(MessageEntity.STATE_PROCESING);
		messageEntity.setSendFlag(true);
		messageEntity.setContent(latitude+"&"+longitude);
		messageEntity.setAddress(address);
		saveMessage(messageEntity);
		mChatAdapter.addNew(messageEntity);
		mPushService.onSendChatMessage(messageEntity, isGroupChat, MessageEntity.TYPE_LOCATION);
		mListView.setSelection(mChatAdapter.getCount());
	}

	@Override
	public void onSendImageMesg(String miniFile,String bigFile) {
		MessageEntity messageEntity = new MessageEntity();
		messageEntity.setId(String.valueOf(System.currentTimeMillis()));
		messageEntity.setSenderId(mUserId);
		messageEntity.setReceiverId(mChatId);
		messageEntity.setType(MessageEntity.TYPE_PICTURE);
		messageEntity.setSendState(MessageEntity.STATE_PROCESING);
		messageEntity.setSendFlag(true);
		messageEntity.setContent(miniFile+"&"+bigFile);
		saveMessage(messageEntity);
		mChatAdapter.addNew(messageEntity);
		mPushService.onSendChatMessage(messageEntity, isGroupChat, MessageEntity.TYPE_PICTURE);
		mListView.setSelection(mChatAdapter.getCount());
	}
	
	/**
	 * 发送语音
	 */
	@Override
	public void onSendVoiceMesg(String path, String timeStr, int time) {
		MessageEntity entity = new MessageEntity();
		entity.setVoiceLength(timeStr);
		entity.setSendFlag(true);
		String name = new File(path).getName();
		entity.setContent(name);
		entity.setSenderId(mUserId);
		entity.setReceiverId(mChatId);
		entity.setSendState(MessageEntity.STATE_PROCESING);
		entity.setType(MessageEntity.TYPE_VOICE);
		saveMessage(entity);
		mChatAdapter.addNew(entity);
		mPushService.onSendChatMessage(entity,isGroupChat,MessageEntity.TYPE_VOICE);
		mListView.setSelection(mChatAdapter.getCount());
	}
	
	@Override
	public void onSelectAll() {
		mChatAdapter.onSelectAll();
	}

	@Override
	public void onDeletAll() {
		List<MessageEntity> list = mChatAdapter.getList();
		if(list.isEmpty())return;
		Message message = mChatHandler.obtainMessage();
		message.obj = new ArrayList<MessageEntity>(list);
		message.what = 1002;
		mChatHandler.sendMessage(message);
	}

	public void onDeletSelect() {
		List<MessageEntity> list = mChatAdapter.onDeletSelectedMesg();
		if(list.isEmpty()) return;
		Message message = mChatHandler.obtainMessage();
		message.obj = list;
		message.what = 1003;
		mChatHandler.sendMessage(message);
	}
	
	/**
	 * 语音播放
	 * @param entity
	 */
	public void onVoicePlay(MessageEntity entity){
		if(StorageUtils.isSDMounted()){
			mPlayingEntity = entity;
			String path = entity.getContent();
			if(path.contains("/")){//远程路径
				String name = StorageUtils.getFileName(path);
				File file = new File(StorageUtils.getVoicePath(),name);
				if(file.exists()){//文件不存在需要去下载
					mediaPlay.play(entity);
				}else{
					HttpRestClient.doHttpDownChatFile(path,new VoiceFileHttpResponseHandler(entity));
				}
			}else{
				mediaPlay.play(entity);
			}
		}
	}
	/**
	 * 播放错误
	 */
	@Override
	public void onPlayError() {
		
	}
	
	/**
	 * 显示聊天大图片
	 * @param str
	 */
	public void onShowBigImage(String str){
		Intent intent = new Intent(this,ImageGalleryActivity.class);
		intent.putExtra(ImageGalleryActivity.URLS_KEY,new String[]{str});
		intent.putExtra(ImageGalleryActivity.TYPE_KEY,0);//0,1单个,多个
		intent.putExtra("type",1);
		startActivityForResult(intent,3000);
	}
	
	/**
	 * 查询在线成员
	 */
	public void onShowGroupListNumber(){
		Intent intent = new Intent(this,SalonMemberListActivity.class);
		intent.putExtra("groupId",mChatId);
		intent.putExtra("type",1000);
		startActivityForResult(intent,-1);
	}
	
	/**
	 * 邀请好友
	 * @param type
	 */
	private void onInviteFriend(int type){
		Intent intent;
		if(type == 3){
			intent = new Intent(this,FriendSearchAboutFriendActivity.class);
		}else{
			intent = new Intent(this,InviteAttentionActivity.class);
		}
		intent.putExtra("groupId",mChatId);
		intent.putExtra("type",type);
		startActivity(intent);
	}

	/**
	 * 显示menu菜单
	 * @param view
	 */
	private void onShowOptionMenu(View view){
		if(mOptionWindow != null && mOptionWindow.isShowing()){
			mOptionWindow.dismiss();
			return;
		}
		if(mChatMenuV == null){
			final LayoutInflater inflater = getLayoutInflater();
			if(isGroupChat){//群聊菜单
				mChatMenuV = inflater.inflate(R.layout.window_menu_chat_group_layout,null);
				ViewGroup group = (ViewGroup)mChatMenuV.findViewById(R.id.contain);
				boolean isGrouper = mUserId.equals(mGroupInfoEntity.getCreateCustomerID());//是否是群主
				for (int i = 0; i < group.getChildCount(); i++) {
					group.getChildAt(i).setOnClickListener(this);
				}
				if(!isGrouper){//非群主菜单
					group.findViewById(R.id.option_popmenu7).setVisibility(View.GONE);
					group.findViewById(R.id.option_popmenu6).setVisibility(View.GONE);
				}
			//单聊菜单	
			}else{
				mChatMenuV = inflater.inflate(R.layout.window_menu_chat_layout,null);
				ViewGroup group = (ViewGroup)mChatMenuV.findViewById(R.id.contain);
				for (int i = 0; i < group.getChildCount(); i++) {
					group.getChildAt(i).setOnClickListener(this);
				}
				boolean isDoctor = mCustomerInfoEntity.isShowDoctorV() || SmartFoxClient.getLoginUserInfo().isShowDoctorV();//是否是医生
//				group.findViewById(R.id.option_popmenu9).setVisibility(isDoctor ? View.VISIBLE : View.GONE);
				group.findViewById(R.id.option_popmenu2).setVisibility(isDoctor ? View.GONE : View.VISIBLE);//聊天背景
//				group.findViewById(R.id.option_popmenu3).setVisibility(isDoctor ? View.VISIBLE : View.GONE);
			}
			if(mOptionWindow == null)mOptionWindow = new PopupWindow(mChatMenuV,LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,true);
			mOptionWindow.setTouchable(true);
			mOptionWindow.setBackgroundDrawable(new BitmapDrawable());
			mOptionWindow.setOutsideTouchable(true);
		}
		mOptionWindow.setContentView(mChatMenuV);
		mOptionWindow.showAsDropDown(view);
	}
	
	View mChangeBgV;//选着背景图
	private void onShowBgPopUpMenu(){// 设置聊天背景图片
		onShowPopUpMenu(1);
	}
	
	View mInviteV;//好友邀请
	private void onShowInvitePopUpMenu(){
		onShowPopUpMenu(0);
	}
	
	private void onShowPopUpMenu(int type){
		View contentView = null;
		final LayoutInflater inflater = getLayoutInflater();
		if(type == 0){//好友邀请
			if(mInviteV == null){
				mInviteV = inflater.inflate(R.layout.window_popup_invite_layout,null);
				ViewGroup group = (ViewGroup)mInviteV;
				for (int i = 0; i < group.getChildCount(); i++) {
					group.getChildAt(i).setOnClickListener(this);
				}
			}
			contentView = mInviteV;
		}if(type == 1){//背景图片
			if(mChangeBgV == null){
				mChangeBgV = inflater.inflate(R.layout.window_popup_choosebg_layout,null);
				ViewGroup group = (ViewGroup)mChangeBgV;
				for (int i = 0; i < group.getChildCount(); i++) {
					group.getChildAt(i).setOnClickListener(this);
				}
			}
			contentView = mChangeBgV;
		}
		if(mPopupWindow == null){
			mPopupWindow = new PopupWindow(contentView,LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT,true);
			mPopupWindow.setTouchable(true);
			mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
			mPopupWindow.setOutsideTouchable(true);
			mPopupWindow.setAnimationStyle(R.style.AnimationPreview);
		}
		mPopupWindow.setContentView(contentView);
		mPopupWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
	}
	
	/**
	 * 
	 * 处理聊天背景图片
	 * @param path
	 */
	private void onHandlerChatBg(String path){
		int size = getDisplayMaxSlidSize();
		Bitmap bitmap = BitmapUtils.decodeBitmap(path,size,size);
		if(bitmap == null)return;
		File file = StorageUtils.createThemeFile();
		if(file != null){
			StorageUtils.saveImageOnImagsDir(bitmap,file);
			SharePreUtils.saveChatBg(this,file.getAbsolutePath(),mUserId,mChatId);
			mChatBgImageV.setBackgroundDrawable(new BitmapDrawable(bitmap));
		}
	}
	
	/**
	 * 地图消息点击
	 * 
	 * @param messageEntity
	 */
	public void onLocationMesgClick(MessageEntity messageEntity) {
		
		Intent intent  = new Intent(this,ChatMapActivity.class);
		String [] str = messageEntity.getContent().split("&");
		intent.putExtra("lo", str[0]);
		intent.putExtra("la", str[1]);
		startActivity(intent);
	}
	
	/**
	 * 设置背景图
	 */
	private void onSetBg(){
		onReleaseBg();
		BitmapDrawable drawable = null;
		String path = SharePreUtils.fatchChatBg(this,mUserId,mChatId);
		if(path == null){//没有图片路径默认设置
			try{
				int resId = 0;
				if(isGroupChat || SmartFoxClient.helperId.equals(mCustomerInfoEntity.getId())){
					resId = R.drawable.chat_bg1;
				}else{
					//医生
//					if(mCustomerInfoEntity.isShowDoctorV()){
//						resId = R.drawable.bj_adrseedocor;
//					}else if(!mCustomerInfoEntity.isShowDoctorV() && SmartFoxClient.getLoginUserInfo().isShowDoctorV()){
//						resId = R.drawable.bj_adrseedisease;
//					}else{
//						resId = R.drawable.chat_bg1;
//					}
					if(mCustomerInfoEntity.isDoctor() || SmartFoxClient.getLoginUserInfo().isDoctor()){
						resId = R.drawable.bj_adrseedisease;
					}else{
						resId = R.drawable.chat_bg1;
					}
				}
				InputStream inputStream = getResources().openRawResource(resId);
				drawable = new BitmapDrawable(inputStream);
				if(inputStream != null)inputStream.close();
			}catch(OutOfMemoryError e){
				e.printStackTrace();
			}catch(Exception e){
			}
		}else{
			File file = new File(path);
			if(file.exists()){//文件存在
				try{
					int size = getDisplayMaxSlidSize();
					Bitmap bitmap = BitmapUtils.decodeBitmap(path, size, size);
					if(bitmap == null)return;
					drawable = new BitmapDrawable(bitmap);
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
		if(drawable != null){
			drawable.setCallback(null);
			mChatBgImageV.setBackgroundDrawable(drawable);
		}
	}
	
	/**
	 * 释放背景图
	 */
	private void onReleaseBg(){
		BitmapDrawable drawable = (BitmapDrawable)mChatBgImageV.getBackground();
		if(drawable == null)return;
		mChatBgImageV.setBackgroundDrawable(null);
		drawable.setCallback(null);
		if(!drawable.getBitmap().isRecycled()){
			drawable.getBitmap().recycle();
		}
		drawable = null;
		System.gc();
	}
	
	/**
	 * 获得屏幕分辨率最大的边
	 * @return
	 */
	private int getDisplayMaxSlidSize(){
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		return Math.max(metrics.heightPixels, metrics.widthPixels);
	}
	
	/**
	 * 点击照片,相册获取
	 * @param v
	 */
	private void onChatBgPhotoClick(View v){
		Intent intent = CropUtils.createPickForFileIntent();
		startActivityForResult(intent,3000);
	}
	
	/**
	 * 点击相机
	 * @param v
	 */
	private void onChatBgCameraClick(View v){
		try{
			mChatBgFile = StorageUtils.createImageFile();
			Uri outUri = Uri.fromFile(mChatBgFile);
			Intent intent = CropUtils.createPickForCameraIntent(outUri);
			startActivityForResult(intent,3001);
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	
}
